package com.fyzk.activity.chongzhi.epay;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class NetUtil {

	/**
	 * 网络连接是否可用
	 */
	private static boolean isConnnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (null != connectivityManager) {
			NetworkInfo networkInfo[] = connectivityManager.getAllNetworkInfo();

			if (null != networkInfo) {
				for (NetworkInfo info : networkInfo) {
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
		return false;
	}


	/**
	 * 网络可用状态下，通过post方式向server端发送请求，并返回响应数据
	 * 
	 * @param market_uri 请求网址
	 * @param params 参数信息
	 * @param context 上下文
	 * @return 响应数据
	 */
	static Respose getResponseForPost(String market_uri, String params, Context context) {
		if (isConnnected(context)) {
			return getResponseForPost(market_uri, params);
		}
		return null;
	}

	/**
	 * 通过post方式向服务器发送请求，并返回响应数据
	 * 
	 * @param market_uri 请求网址
	 * @param params 参数信息
	 * @return 响应数据
	 */
	static Respose getResponseForPost(String market_uri, String params) {

		Log.i("wiki", "market_uri:"+market_uri);
		Log.i("wiki", "params:"+params);
		if (null == market_uri || "" == market_uri) {
			return null;
		}
		 
		HttpPost request = new HttpPost(market_uri);
		ByteArrayInputStream byteArrayInputStream = null;
		try {
			byte[] buffer = params.getBytes();
			byteArrayInputStream = new ByteArrayInputStream(buffer);
			request.setEntity(new InputStreamEntity(byteArrayInputStream, buffer.length));
			return getRespose(request);
		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			if(byteArrayInputStream != null){
				try {
					byteArrayInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 响应客户端请求
	 * 
	 * @param request 客户端请求get/post
	 * @return 响应数据
	 */
	private static Respose getRespose(HttpUriRequest request) {
		try {
			Log.i("wiki", "连接客户服务器");
			Respose yhjRespose = new Respose();
			HttpClient client = newHttpsClient();
			HttpResponse httpResponse = client.execute(request);
			yhjRespose.statusCode = httpResponse.getStatusLine().getStatusCode();
			yhjRespose.resposeString = getContentForString(httpResponse);
			Log.i("wiki", "statusCode"+yhjRespose.statusCode);
			Log.i("wiki", "resposeString"+yhjRespose.resposeString);
			return yhjRespose;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	static public HttpClient newHttpsClient() {
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);  
  
            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            HttpConnectionParams.setConnectionTimeout(params, 10000);
            HttpConnectionParams.setSoTimeout(params, 10000);
  
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
  
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  
            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }  
    }  
  
    private static class MySSLSocketFactory extends SSLSocketFactory {
        SSLContext sslContext = SSLContext.getInstance("TLS");
  
        public MySSLSocketFactory(KeyStore truststore)
                throws NoSuchAlgorithmException, KeyManagementException,
				KeyStoreException, UnrecoverableKeyException {
            super(truststore);  
  
            TrustManager tm = new X509TrustManager() {

				@Override
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}

				@Override
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
					
				}

				@Override
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}  
            };  
  
            sslContext.init(null, new TrustManager[] { tm }, null);
        }  
  
        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
                throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);  
        }  
  
        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();  
        }  
    }  
	
	/**
	 * 读取HttpResponse的内容
	 * @return
	 * @throws Exception
	 */
	private static String getContentForString(HttpResponse httpResponse) throws Exception {
        String responseContext = null;
        InputStream in = null;
        InputStreamReader reader = null;
        BufferedReader buffer = null;
        StringBuilder str = new StringBuilder();
        try{
            in = httpResponse.getEntity().getContent();
            if (null != in) {
            	reader = new InputStreamReader(in,"UTF-8");
                buffer = new BufferedReader(reader);
                String line=null;
                while((line=buffer.readLine())!=null){
                    str.append(line);
                }
                responseContext = str.toString();
			}
        }finally{
        	if(buffer != null){
        		buffer.close();
        	}
        }
        return responseContext;
    }
	
}

